package city.spring.modules.medicalstation.drugdepositDrugExt.controller;

import city.spring.modules.medicalstation.drugdeposit.entity.DrugdepositEntity;
import city.spring.modules.medicalstation.drugdeposit.service.DrugdepositService;
import city.spring.modules.medicalstation.drugdepositDrugExt.entity.DrugdepositDrugExtEntity;
import city.spring.modules.medicalstation.drugdepositDrugExt.repository.DrugdepositDrugExtRepository;
import city.spring.modules.medicalstation.drugdepositDrugExt.service.DrugdepositDrugExtService;
import city.spring.modules.medicalstation.drugdepositDrugExt.vo.DrugdepositDrugVO;
import city.spring.modules.medicalstation.drugwarehouse.entity.DrugwarehouseEntity;
import city.spring.modules.medicalstation.drugwarehouse.service.DrugwarehouseService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Controller：药品缴存与药品关联表
 *
 * @author 谢金婷
 * @date 2020-10-13 16:56:39
 */
@RestController
@RequestMapping("/drugdeposit/{drugdepositId}/drug")
public class DrugdepositDrugExtController extends ApiController {
    private final DrugdepositDrugExtService drugdepositDrugExtService;
    private final DrugdepositDrugExtRepository drugdepositDrugExtRepository;
    private final DrugdepositService drugdepositService;
    private final DrugwarehouseService drugwarehouseService;

    /**
     * 实体类可排序字段
     */
    private final List<SFunction<DrugdepositDrugExtEntity, ?>> entityOrderFields;

    public DrugdepositDrugExtController(DrugdepositDrugExtService drugdepositDrugExtService, DrugdepositDrugExtRepository drugdepositDrugExtRepository, DrugdepositService drugdepositService, DrugwarehouseService drugwarehouseService) {
        this.drugdepositDrugExtService = drugdepositDrugExtService;
        this.drugdepositDrugExtRepository = drugdepositDrugExtRepository;
        this.drugdepositService = drugdepositService;
        this.drugwarehouseService = drugwarehouseService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(DrugdepositDrugExtEntity::getId);
        entityOrderFields.add(DrugdepositDrugExtEntity::getDrugdepositId);
        entityOrderFields.add(DrugdepositDrugExtEntity::getDrugId);
        entityOrderFields.add(DrugdepositDrugExtEntity::getDrugCode);
        entityOrderFields.add(DrugdepositDrugExtEntity::getDepositquantity);
        entityOrderFields.add(DrugdepositDrugExtEntity::getUnit);
        entityOrderFields.add(DrugdepositDrugExtEntity::getStatus);
        entityOrderFields.add(DrugdepositDrugExtEntity::getGmtCreate);
        entityOrderFields.add(DrugdepositDrugExtEntity::getGmtModified);
    }

    @ModelAttribute
    public void getDrugdepositId(@PathVariable String drugdepositId) {
        if (drugdepositId == null) {
            throw new RuntimeException("药品缴存单ID必须不为空");
        }
        System.out.println("drugdepositId" + drugdepositId);
    }

    /**
     * 获取全部的 <strong>药品缴存与药品关联表</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, DrugdepositDrugExtEntity entity) {
        LambdaQueryChainWrapper<DrugdepositDrugExtEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

//    /**
//     * 分页获取 <strong>药品缴存与药品关联表</strong> 列表
//     *
//     * @param pageable 分页参数信息
//     */
//    @GetMapping
//    public Object list(@PageableDefault Pageable pageable, DrugdepositDrugExtEntity entity) {
//        LambdaQueryChainWrapper<DrugdepositDrugExtEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<DrugdepositDrugExtEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        return success(page);
//    }

    @GetMapping
    public Object list(@PathVariable String drugdepositId) {
        return success(drugdepositDrugExtRepository.getDepositDrugs(drugdepositId));
    }

//    /**
//     * 获取一个 <strong>药品缴存与药品关联表</strong>
//     *
//     * @param id 主键ID
//     */
//    @GetMapping("{id}")
//    public Object info(@PathVariable String id) {
//        return success(drugdepositDrugExtService.getById(id));
//    }

    @GetMapping("{extId}")
    public Object getInfo(@PathVariable String drugdepositId, @PathVariable String extId) {
        return success(drugdepositDrugExtRepository.getDepositDrug(drugdepositId, extId));
    }


    //    /**
//     * 添加一个 <strong>药品缴存与药品关联表</strong>
//     *
//     * @param entity 修改后的信息
//     */
//    @PostMapping
//    public Object add(@RequestBody DrugdepositDrugExtEntity entity) {
//        drugdepositDrugExtService.saveDrugdepositDrugExt(entity);
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
//        return new ResponseEntity<>(headers, HttpStatus.CREATED);
//    }
    @PostMapping
    public Object addAll(@PathVariable String drugdepositId, @RequestBody List<DrugdepositDrugExtEntity> drugs) {

        // 查出已有的数据
        List<DrugdepositDrugVO> dbDrugs = drugdepositDrugExtRepository.getDepositDrugs(drugdepositId);
        // 数据库已经存在的班次列表
        Set<Integer> dbDrugIdsSet = dbDrugs.stream()
                .map(DrugdepositDrugExtEntity::getDrugId)
                .collect(Collectors.toSet());
        // 过滤掉已经存在数据库的数据
        List<DrugdepositDrugExtEntity> needSaveDrugs = drugs.stream()
                .filter(item -> {
                    item.setDrugdepositId(drugdepositId);
                    Integer drugId = item.getDrugId();
                    // 过滤出不存在数据库中的数据
                    return drugId != null && !dbDrugIdsSet.contains(drugId);
                }).collect(Collectors.toList());
        DrugdepositEntity drugdepositEntity = drugdepositService.getById(drugdepositId);
        for (DrugdepositDrugExtEntity drugdepositDrugExtEntity : needSaveDrugs) {
            drugdepositDrugExtEntity.setOldmanId(drugdepositEntity.getOldmanId());
            drugdepositDrugExtEntity.setStatus(1);
            drugdepositDrugExtEntity.setTotal(drugdepositDrugExtEntity.getUnitprice().multiply(drugdepositDrugExtEntity.getDepositquantity()));
            if (drugdepositEntity.getDepositmethod().equals("本人缴存") || drugdepositEntity.getDepositmethod().equals("家属缴存")) {
                DrugwarehouseEntity drugwarehouseEntity = new DrugwarehouseEntity();
//                drugwarehouseEntity.setStorehouseId(medicinedelivery.getWstorehouseId());
                drugwarehouseEntity.setMedicineId(drugdepositDrugExtEntity.getDrugId());
                drugwarehouseEntity.setMedicineCode(drugdepositDrugExtEntity.getDrugCode());
                drugwarehouseEntity.setQuantity(drugdepositDrugExtEntity.getDepositquantity());
                drugwarehouseEntity.setUnit(drugdepositDrugExtEntity.getSpecifications());
                drugwarehouseEntity.setUnitprice(drugdepositDrugExtEntity.getUnitprice());
                drugwarehouseEntity.setIswarehouse(2);
                drugwarehouseEntity.setApprovalStatus(1);
                drugwarehouseEntity.setWarehousingmethod(drugdepositEntity.getDepositmethod());
                drugwarehouseService.saveDrugwarehouse(drugwarehouseEntity);
            }
        }
        if (!needSaveDrugs.isEmpty()) {
            drugdepositDrugExtService.saveOrUpdateBatch(needSaveDrugs);
        }

        return success(null);
    }

    //    /**
//     * 修改一个 <strong>药品缴存与药品关联表</strong>
//     *
//     * @param id     主键ID
//     * @param entity 修改后的信息
//     */
//    @PutMapping("{id}")
//    public Object update(@PathVariable String id, @RequestBody DrugdepositDrugExtEntity entity) {
//        entity.setId(id);
//        drugdepositDrugExtService.updateDrugdepositDrugExt(entity);
//        return new ResponseEntity<>(HttpStatus.OK);
//    }
    @PutMapping("{extId}")
    public Object update(@PathVariable String drugdepositId, @PathVariable String extId, @RequestBody DrugdepositDrugExtEntity extEntity) {
        extEntity.setId(extId);
        extEntity.setDrugdepositId(drugdepositId);
        drugdepositDrugExtService.updateDrugdepositDrugExt(extEntity);
        return success(null);
    }

    /**
     * 删除一个 <strong>药品缴存与药品关联表</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        drugdepositDrugExtService.deleteDrugdepositDrugExt(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>药品缴存与药品关联表</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        drugdepositDrugExtService.deleteDrugdepositDrugExt(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<DrugdepositDrugExtEntity> buildLambdaQuery(DrugdepositDrugExtEntity entity) {
        LambdaQueryChainWrapper<DrugdepositDrugExtEntity> lambdaQuery = drugdepositDrugExtService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), DrugdepositDrugExtEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDrugdepositId()), DrugdepositDrugExtEntity::getDrugdepositId, entity.getDrugdepositId());
        lambdaQuery.eq(entity.getDrugId() != null, DrugdepositDrugExtEntity::getDrugId, entity.getDrugId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDrugCode()), DrugdepositDrugExtEntity::getDrugCode, entity.getDrugCode());
        lambdaQuery.eq(entity.getDepositquantity() != null, DrugdepositDrugExtEntity::getDepositquantity, entity.getDepositquantity());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUnit()), DrugdepositDrugExtEntity::getUnit, entity.getUnit());
        lambdaQuery.eq(entity.getStatus() != null, DrugdepositDrugExtEntity::getStatus, entity.getStatus());
        lambdaQuery.eq(entity.getGmtCreate() != null, DrugdepositDrugExtEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, DrugdepositDrugExtEntity::getGmtModified, entity.getGmtModified());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<DrugdepositDrugExtEntity> buildQuery(DrugdepositDrugExtEntity entity) {
        QueryWrapper<DrugdepositDrugExtEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getDrugdepositId()), "drugdeposit_id", entity.getDrugdepositId());
        wrapper.eq(entity.getDrugId() != null, "drug_id", entity.getDrugId());
        wrapper.like(StringUtils.isNotBlank(entity.getDrugCode()), "drug_code", entity.getDrugCode());
        wrapper.eq(entity.getDepositquantity() != null, "quantity", entity.getDepositquantity());
        wrapper.like(StringUtils.isNotBlank(entity.getUnit()), "unit", entity.getUnit());
        wrapper.eq(entity.getStatus() != null, "status", entity.getStatus());
        wrapper.eq(entity.getGmtCreate() != null, "gmt_create", entity.getGmtCreate());
        wrapper.eq(entity.getGmtModified() != null, "gmt_modified", entity.getGmtModified());
        return wrapper;
    }

    /**
     * 退缴功能
     *
     * @param id
     * @param entity
     * @return
     */
    @PutMapping("/refundDeposit/{id}")
    public Object refundDeposit(@PathVariable String id, @RequestBody DrugdepositDrugExtEntity entity) {
        drugdepositDrugExtService.refundDeposit(id, entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

}
